<template>
  <div @submit="handleSubmit">
    <a-form :form="form">
      <!--companyId-->
      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属公司">
        <a-select
          @change="handleProvinceChange"
          v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择所属公司' }],initialValue:defaultCompany}]"
          placeholder="请选择所属公司">
          <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
            {{company.name}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="商户">
        <a-select
          v-decorator="[ 'subMchId', {rules: [{ required: true, message: '请选择商户' }]}]"
          placeholder="请选择商户">
          <a-select-option :value="merchant.subMchId" v-for="merchant in merchantList" :key="merchant.subMchId">
            {{merchant.name}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="适用商户">
        <a-tree-select
          style="width:300px"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder='请选择商户'
          allowClear
          multiple
          treeDefaultExpandAll
          :treeData="treeData"
          v-model="value"
          v-decorator="['key',{rules: [{ required: true, message: '请选择商户' }]}]"
        >
          <span style="color:#08c" slot="title" slot-scope="{key}"
          >
            {{value}}
          </span>>
        </a-tree-select>
      </a-form-item>-->

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="团购券批次名称">
        <a-input placeholder="团购券批次名称"
                 v-decorator="[ 'stockName', {rules: [{ required: true, message: '请输入批次号' }]}]"
        ></a-input>
      </a-form-item>
      <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次归属商户号">
        <a-input placeholder="批次归属商户号"
                 v-decorator="[ 'belongMerchant', {rules: [{ required: true, message: '请输入批次号' }]}]"
        ></a-input>
      </a-form-item>-->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="适用团购范围">
        <a-input placeholder="适用团购范围"
                 v-decorator="[ 'goodsName', {rules: [{ required: true, message: '请输入批次号' }]}]"
        ></a-input>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次类型">
        <a-select @change="stockTypeChange"
                  v-decorator="[ 'stockType', {rules: [{ required: true, message: '请选择批次类型' }]}]"
        >
          <a-select-option value="NORMAL">固定面额满减券批次</a-select-option>
          <a-select-option value="DISCOUNT">折扣券批次</a-select-option>
          <a-select-option value="EXCHANGE">换购券批次</a-select-option>
        </a-select>
      </a-form-item>


      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="券code模式">
        <a-select
          v-decorator="[ 'couponCodeMode', {rules: [{ required: true, message: '请选择券code模式' }]}]"
        >
          <a-select-option value="WECHATPAY_MODE">系统分配券code</a-select-option>
          <a-select-option value="MERCHANT_API">商户发放时接口指定券code</a-select-option>
          <a-select-option value="MERCHANT_UPLOAD">商户上传自定义code</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规则">
        <a-collapse v-model="activeKey">
          <a-collapse-panel header="核销规则" key="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="券可核销时间">
              <a-range-picker
                :format="dateFormat"
                v-decorator="[ 'validTime', {rules: [{ required: true, message: '请选择时间' }]}]"
              />
            </a-form-item>

            <a-form-item v-if="stockType=='NORMAL'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠金额">
              <a-input placeholder="优惠金额"
                       v-decorator="[ 'discount_amount', {rules: [{ required: true, message: '请输入优惠金额' }]}]"
              ></a-input>
            </a-form-item>
            <a-form-item v-if="stockType=='DISCOUNT'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="折扣比例">
              <a-input placeholder="折扣比例"
                       v-decorator="[ 'discount_percent', {rules: [{ required: true, message: '请输入折扣比例' }]}]"
              ></a-input>
            </a-form-item>
            <a-form-item v-if="stockType=='EXCHANGE'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="单品换购价">
              <a-input placeholder="单品换购价"
                       v-decorator="[ 'exchange_price', {rules: [{ required: true, message: '请输入单品换购价' }]}]"
              ></a-input>
            </a-form-item>

            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="消费门槛">
              <a-input placeholder="消费门槛"
                       v-decorator="[ 'transaction_minimum', {rules: [{ required: true, message: '请输入消费门槛' }]}]"
              ></a-input>
            </a-form-item>

            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次类型">
              <a-select
                v-decorator="[ 'use_method', {rules: [{ required: true, message: '请选择批次类型' }]}]"
              >
                <a-select-option value="OFF_LINE">线下滴码核销</a-select-option>
                <a-select-option value="MINI_PROGRAMS">线上小程序核销</a-select-option>
                <a-select-option value="USER_SELF">用户自主核销</a-select-option>
              </a-select>
            </a-form-item>

            <!--<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="小程序appid">
              <a-input placeholder="小程序appid"
                       v-decorator="[ 'mini_programs_appid']"
              ></a-input>
            </a-form-item>

            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="小程序path">
              <a-input placeholder="小程序path"
                       v-decorator="[ 'mini_programs_path']"
              ></a-input>
            </a-form-item>-->
          </a-collapse-panel>
          <a-collapse-panel header="发放规则" key="2" :disabled="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次总预算">
              <a-input placeholder="批次总预算"
                       v-decorator="[ 'max_amount', {rules: [{ required: true, message: '请输入批次总预算' }]}]"
              ></a-input>
            </a-form-item>

            <a-form-item v-if="stockType=='DISCOUNT'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次最大发放个数">
              <a-input placeholder="批次最大发放个数"
                       v-decorator="[ 'max_coupons', {rules: [{ required: true, message: '请输入批次最大发放个数' }]}]"
              ></a-input>
            </a-form-item>

            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户最大可领个数">
              <a-input placeholder="用户最大可领个数"
                       v-decorator="[ 'max_coupons_per_user', {rules: [{ required: true, message: '请输入用户最大可领个数' }]}]"
              ></a-input>
            </a-form-item>
          </a-collapse-panel>
        </a-collapse>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="团购券价值">
        <a-input placeholder="团购券价值"
                 v-decorator="[ 'value', {rules: [{ required: true, message: '请输入商家券价值' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="团购券使用最低限额">
        <a-input placeholder="团购券使用最低限额"
                 v-decorator="[ 'businessCouponMininumn', {rules: [{ required: true, message: '请输入商家券使用最低限额' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="获取到的积分">
        <a-input placeholder="获取到的积分"
                 v-decorator="[ 'points', {rules: [{ required: false, message: '请输入获取到的积分'}],initialValue:'0',pattern: new RegExp(/^[0-9]\d*$/,'g')}]"
        ></a-input>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="团购券图"
      >
        <a-upload
          :action="this.$baseURL+'/common/upload/uploadImg'"
          listType="picture-card"
          :fileList="fileList"
          @preview="uploadPreview"
          @change="uploadChange"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus"/>
            <div class="ant-upload-text">上传团购券图</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
          <img alt="example" style="width: 100%" :src="previewImage"/>
        </a-modal>
      </a-form-item>

      <!--note 简介描述 -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="简介描述">
        <!--v-model="content"-->
        <quill-editor
          v-model="content "
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @change="onEditorChange($event)">
        </quill-editor>
      </a-form-item>

      <a-form-item
        v-bind="buttonCol"
      >
        <a-row>
          <a-col span="6">
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-col>
          <a-col span="10">
            <a-button @click="handleGoBack">返回</a-button>
          </a-col>
          <a-col span="8"></a-col>
        </a-row>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>


  import pick from 'lodash.pick'
  import { save } from '@/api/productService/businesscoupon'
  import { selectAll,selectMerchantByCompanyId } from '@/api/productService/product'
  import { quillEditor } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {

    components: {
      quillEditor
    },
    props: {
      record: {
        default: ''
      }
    },
    data() {
      return {
        activeKey: ['1', '2'],
        dateFormat: 'YYYY/MM/DD',
        value: [],
        stockType: 'NORMAL',
        treeData: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        buttonCol: {
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 12, offset: 5 }
          }
        },
        storeIds: '',
        companyList: [],
        visible: false,
        form: this.$form.createForm(this),
        merchantList: [],
        previewImage: '',
        previewVisible: false,
        // mode: 'multiple',
        defaultCompany: '',
        //图片上传
        fileList: [],
        mdl: {},
        businessCouponPicUrl: '',
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike', 'clean'],
              ['blockquote', 'code-block'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }]
            ]
          }
        },
        content: ''
      }
    },
    created() {
      this.getAllCompany()
      if (this.record != '') {
        this.loadEditInfo(this.record)
      }
    },

    methods: {
      loadEditInfo(record) {
        record.value = record.storeCodes
        this.mdl = Object.assign({}, record)
        this.getAllCompany()
        this.isDisabled = true
        this.content = this.escapeStringHTML(record.note)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, 'companyId', 'couponStockId', 'paySubMchId', 'name', 'type', 'value'))
        })

      },
      handleGoBack() {
        this.$emit('onGoBack')
      },
      stockTypeChange(value) {
        this.stockType = value
      },
      uploadCancel() {
        this.previewVisible = false
      },
      getAllCompany: function() {
        const _this = this
        selectAll().then(res => {
          if (res.code === 200) {
            this.companyList = res.result
            this.defaultCompany = this.companyList[0].id
            let querycompanyId
            /*报错的原因*/
            if (_this.record.companyId != undefined) {
              /*不为空就执行编辑*/
              querycompanyId = _this.record.companyId
            } else {
              /*为空就添加*/
              querycompanyId = res.result[0].id
            }
            this.getMerchant(querycompanyId)
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      onEditorBlur() {
      }, // 失去焦点事件
      onEditorFocus() {
      }, // 获得焦点事件
      onEditorChange() {
      }, // 内容改变事件
      // 转码
      escapeStringHTML(str) {
        if (str) {
          str = str.replace(/&lt;/g, '<')
          str = str.replace(/&gt;/g, '>')
          return str
        }

      },
      //公司改变
      handleProvinceChange(value) {
        if (value) {
          this.getMerchant(value)
        }
      },
      getMerchant: function(companyId) {
        const _this = this
        selectMerchantByCompanyId(companyId).then(res => {
          if (res.code === 200) {
            if (res.result == null) {
              return
            }
            _this.merchantList = res.result

          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        const _this = this
        this.fileList = info.fileList
        if (info.file.status === 'done') {
          this.fileList.pop()
          this.fileList.push(info.file)
          _this.businessCouponPicUrl = info.file.response.url
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          deletePic(info.file.uid).then(res => {
          })
        }
      },
      handleSubmit() {
        const _this = this
        // 触发表单验证
        _this.form.validateFields((err, values) => {
          const params = {}
          params.companyId = values.companyId
          params.stockName = values.stockName
          params.belongMerchant = values.subMchId
          params.goodsName = values.goodsName
          params.stockType = values.stockType
          params.couponCodeMode = values.couponCodeMode

          /*核销规则  -- start*/
          const couponUseRule = {}
          const coupon_available_time = {}
          coupon_available_time.available_begin_time = values.validTime[0]
          coupon_available_time.available_end_time =  values.validTime[1]
          couponUseRule.coupon_available_time = coupon_available_time

          if(values.stockType=='NORMAL'){
            const fixed_normal_coupon = {}
            fixed_normal_coupon.discount_amount=parseInt(values.discount_amount)
            fixed_normal_coupon.transaction_minimum =parseInt(values.transaction_minimum)
            couponUseRule.fixed_normal_coupon=fixed_normal_coupon
          }else if(values.stockType=='DISCOUNT'){
            const discount_coupon = {}
            discount_coupon.discount_percent = parseInt(values.discount_percent)
            discount_coupon.transaction_minimum = parseInt(values.transaction_minimum)
            couponUseRule.discount_coupon = discount_coupon
          }else if(values.stockType=='EXCHANGE'){
            const exchange_coupon = {}
            exchange_coupon.exchange_price=parseInt(values.exchange_price)
            exchange_coupon.transaction_minimum =parseInt(values.transaction_minimum)
            couponUseRule.exchange_coupon=exchange_coupon
          }
          couponUseRule.use_method=values.use_method
          params.couponUseRule = couponUseRule
          /*核销规则  -- end*/

          /*发放规则 -- start*/
          const stock_send_rule = {}
          if(values.stockType=='DISCOUNT'){
            stock_send_rule.max_coupons = parseInt(values.max_coupons)
          }
          stock_send_rule.max_amount = parseInt(values.max_amount)
          stock_send_rule.max_coupons_per_user = parseInt(values.max_coupons_per_user)
          params.stockSendRule = stock_send_rule
          /*发放规则 -- end*/
          params.businessCouponPicUrl = _this.businessCouponPicUrl
          params.note = _this.content
          params.value = values.value
          params.businessCouponMininumn = values.businessCouponMininumn
          console.log('组装数据结构：', params)
          // 验证表单没错误
          if (!err) {
            save(params).then((res) => {
              if (res.code === 200) {
                _this.$message.success('添加成功')
                this.$emit('onGoBack')
              } else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })

      }

    }

  }
</script>

<style>
  .ql-container {
    height: 300px;
  }
</style>